package com.orion.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import com.orion.config.Oauth2JdbcAuthorizationServerConfig;
import com.orion.domain.OauthClientDetails;
import com.orion.service.OauthClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登记clientId、secretId、callback_uri、scope、resourceIds、authorities
 *
 * @author Administrator
 * @date 2021/9/24
 */
@RestController
@RequestMapping("/oauthClient")
public class RegisterClientController {

    @Autowired
    private OauthClientDetailsService oauthClientDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/add")
    public String addClinet(String callbackUri) {
        String clientId = RandomUtil.randomString(8);
        String secretId = RandomUtil.randomString(10);

        OauthClientDetails oauthClientDetails = new OauthClientDetails();
        oauthClientDetails.setClientId(clientId);
        oauthClientDetails.setClientSecret(passwordEncoder.encode(secretId));

        oauthClientDetails.setRawSecret(secretId);
        oauthClientDetails.setWebServerRedirectUri(callbackUri);
        oauthClientDetails.setAccessTokenValidity(Oauth2JdbcAuthorizationServerConfig.ACCESS_TOKEN_VALID_SECONDS);
        oauthClientDetails.setRefreshTokenValidity(Oauth2JdbcAuthorizationServerConfig.REFRESH_TOKEN_VALID_SECONDS);
        oauthClientDetails.setAutoapprove(Boolean.TRUE.toString());

        //AdditionalInformation必须json格式
        JSONObject additionalInformationJsonObject = new JSONObject();
        additionalInformationJsonObject.put("orionKey","orionVal");
        additionalInformationJsonObject.put("lilyKey","llcVal");
        String additionalInformation = additionalInformationJsonObject.toString();

        oauthClientDetails.setAdditionalInformation(additionalInformation);
        oauthClientDetails.setScope("user_info");
        oauthClientDetails.setResourceIds("hahaRsId");
        oauthClientDetails.setAuthorizedGrantTypes("authorization_code,password,refresh_token");
        oauthClientDetails.setAuthorities("author1,author2");
        oauthClientDetailsService.save(oauthClientDetails);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("clientId", clientId);
        jsonObject.put("secretId", secretId);

        return jsonObject.toString();
    }
}
